<?php
require_once ("secure_area.php");
require_once ("interfaces/idata_controller.php");
require_once APPPATH.'libraries/PHPExcel.php';
class Items extends Secure_area implements iData_controller
{
	function __construct()
	{
		parent::__construct('items');
	}

	function index()
	{
		$config['base_url'] = site_url('/items/index');
		$config['total_rows'] = $this->Item->count_all();
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$this->pagination->initialize($config);
		
		$data['controller_name']=strtolower(get_class());
		$data['form_width']=$this->get_form_width();
		$data['manage_table']=get_items_manage_table( $this->Item->get_all( $config['per_page'], $this->uri->segment( $config['uri_segment'] ) ), $this );
		$this->load->view('items/manage',$data);
	}

	function refresh()
	{  
        $is_deleted=$this->input->post('is_deleted'); // Parq 131215	
        
		$data['search_section_state']=$this->input->post('search_section_state');
		$data['is_deleted']=$this->input->post('is_deleted'); // Parq 131215
		$data['controller_name']=strtolower(get_class());
		$data['form_width']=$this->get_form_width(); 
		$data['manage_table']=get_items_manage_table($this->Item->get_all_filtered($is_serialized,$no_description,$search_custom,$is_deleted),$this);//GARRISON MODIFIED 4/13/2013, Parq 131215
		$this->load->view('items/manage',$data);
	}

	function find_item_info()
	{
		$item_number=$this->input->post('scan_item_number');
		echo json_encode($this->Item->find_item_info($item_number));
	}

	function search()
	{
		$search=$this->input->post('search');
		$data_rows=get_items_manage_table_data_rows($this->Item->search($search),$this);
		echo $data_rows;
	}

	/*
	Gives search suggestions based on what is being searched for
	*/
	function suggest()
	{
		$suggestions = $this->Item->get_search_suggestions($this->input->post('q'),$this->input->post('limit'));
		echo implode("\n",$suggestions);
	}
	
	function item_search()
	{
		$suggestions = $this->Item->get_item_search_suggestions($this->input->post('q'),$this->input->post('limit'),'warehouse');
		echo implode("\n",$suggestions);
	}
	
	/*
	Gives search suggestions based on what is being searched for
	*/
	function suggest_category()
	{
		$suggestions = $this->Item->get_category_suggestions($this->input->post('q'));
		echo implode("\n",$suggestions);
	}
	
	function suggest_group()
	{
		$suggestions = $this->Item->get_group_suggestions($this->input->post('q'));
		echo implode("\n",$suggestions);
	}
		
	function get_row()
	{
		$item_id = $this->input->post('row_id');
		$data_row=get_item_data_row($this->Item->get_info($item_id),$this);
		echo $data_row;
	}

	function view($item_id=-1)
	{
		$data['item_info']=$this->Item->get_info($item_id);
		
		$this->load->view("items/form",$data);
	}

	
	function count_details($item_id=-1)
	{
		$data['item_info']=$this->Item->get_info($item_id);
                
		$this->load->view("items/count_details",$data);
	} //------------------------------------------- Ramel

	function generate_barcodes($item_ids)
	{
		$result = array();

		$item_ids = explode(':', $item_ids);
		foreach ($item_ids as $item_id)
		{
			$item_info = $this->Item->get_info($item_id);

			$result[] = array('name' =>$item_info->name, 'id'=> $item_id);
		}

		$data['items'] = $result;
		$this->load->view("barcode_sheet", $data);
	}

	function save($item_id=-1)
	{
        //Save item data
		$item_data = array(
		'name'=>$this->input->post('name'),
		'category'=>$this->input->post('category'),
		'group'=>$this->input->post('group'),
		'item_number'=>$this->input->post('item_number'),
		'cost_price'=>$this->input->post('unit_price'),
		'unit_price'=>$this->input->post('unit_price'),
		'quantity'=>$this->input->post('quantity'),
		'deleted'=>$this->input->post('is_deleted'),  /** Parq 131215 **/
		);
		
		$employee_id=$this->Employee->get_logged_in_employee_info()->person_id;
		$cur_item_info = $this->Item->get_info($item_id);
		
		$this->form_validation->set_rules('name','name','required');
		$this->form_validation->set_rules('category','category','required');
		$this->form_validation->set_rules('group','group','required');
		$this->form_validation->set_rules('item_number','item_number','numeric|required');
		$this->form_validation->set_rules('unit_price','unit_price','is_natural_no_zero|required');
		$this->form_validation->set_rules('quantity','quantity','greater_than[0]|required');

		if(!$this->form_validation->run() == FALSE && $this->Item->save($item_data,$item_id))
		{
			//New item
			if($item_id==-1)
			{
				echo json_encode(array('success'=>true,'message'=>$this->lang->line('items_successful_adding').' '.
				$item_data['name'],'item_id'=>$item_data['item_id']));
				$item_id = $item_data['item_id'];
			}
			else //previous item
			{
				echo json_encode(array('success'=>true,'message'=>$this->lang->line('items_successful_updating').' '.
				$item_data['name'],'item_id'=>$item_id));
			}      
		}
		else//failure
		{
			echo json_encode(array('success'=>false,'message'=>$this->lang->line('items_error_adding_updating').' '.
			$item_data['name'],'item_id'=>-1));
		}

	}
	
	//Ramel Inventory Tracking
	function save_inventory($item_id=-1)
	{	
		$employee_id=$this->Employee->get_logged_in_employee_info()->person_id;
		$cur_item_info = $this->Item->get_info($item_id);
        $location_id = $this->input->post('stock_location');
		$inv_data = array
		(
			'trans_date'=>date('Y-m-d H:i:s'),
			'trans_items'=>$item_id,
			'trans_user'=>$employee_id,
			'trans_location'=>$location_id,
			'trans_comment'=>$this->input->post('trans_comment'),
			'trans_inventory'=>$this->input->post('newquantity')
		);
		$this->Inventory->insert($inv_data);
		
		//Update stock quantity
		
		$item_quantity= $this->Item_quantities->get_item_quantity($item_id,$location_id);
		$item_quantity_data = array(
		'item_id'=>$item_id,
		'location_id'=>$location_id,
		'quantity'=>$item_quantity->quantity + $this->input->post('newquantity')
		);
		if($this->Item_quantities->save($item_quantity_data,$item_id,$location_id))
		{			
			echo json_encode(array('success'=>true,'message'=>$this->lang->line('items_successful_updating').' '.
			$cur_item_info->name,'item_id'=>$item_id));
		}
		else//failure
		{	
			echo json_encode(array('success'=>false,'message'=>$this->lang->line('items_error_adding_updating').' '.
			$cur_item_info->name,'item_id'=>-1));
		}

	}//---------------------------------------------------------------------Ramel

	function delete()
	{
		$items_to_delete=$this->input->post('ids');

		if($this->Item->delete_list($items_to_delete))
		{
			echo json_encode(array('success'=>true,'message'=>$this->lang->line('items_successful_deleted').' '.
			count($items_to_delete).' '.$this->lang->line('items_one_or_multiple')));
		}
		else
		{
			echo json_encode(array('success'=>false,'message'=>$this->lang->line('items_cannot_be_deleted')));
		}
	}
	
	function excel_import()
	{
		$this->load->view("items/upload_form", array('error' => ' ' ));
	}
	function do_upload() {
		$msg = 'do_excel_import';
		$failCodes = array ();
		
		$config['upload_path'] = './uploads/';
		$config['allowed_types'] = 'xls|xlsx';
		$config['max_size']	= '100000';
		
		$this->load->library ( 'upload', $config );
		if (! $this->upload->do_upload ()) {
			var_dump($this->upload->data());
			$msg = $this->lang->line ( 'items_excel_import_failed' );
			echo $this->upload->display_errors();
			echo json_encode ( array (
					'success' => false,
					'message' => $msg 
			) );
			return;
		} else {
			
			
			$infile = $this->upload->data();
			$inputFileType = 'Excel5';
			$inputFileName = $infile['full_path'];
			
			$objReader = PHPExcel_IOFactory::createReader ( $inputFileType );
			$objPHPExcelReader = $objReader->load ( $inputFileName );
			
			$loadedSheetNames = $objPHPExcelReader->getSheetNames ();
			
			$objWriter = PHPExcel_IOFactory::createWriter ( $objPHPExcelReader, 'CSV' );
			
			foreach ( $loadedSheetNames as $sheetIndex => $loadedSheetName ) {
				$objWriter->setSheetIndex ( $sheetIndex );
				$objWriter->save ( $infile['file_path'].$infile['raw_name'].'.csv' );
			}
			
			if (($handle = fopen($infile['file_path'].$infile['raw_name'].'.csv', "r")) !== FALSE) {
				// Skip first row
				fgetcsv ( $handle );
				
				$i = 1;
				while ( ($data = fgetcsv ( $handle )) !== FALSE ) {
					$item_data = array (
							'item_number' => $data [0],
							'category' => $data [1],
							'group' => $data [2],
							'name' => $data [3],
							'cost_price' => $data [4],
							'unit_price' => $data [4],
							'quantity' => $data[5]
					);
					$item_number = $data [0];
					
					if ($item_number != "") {
						$item_data ['item_number'] = $item_number;
					}
					
					if (!$this->Item->save ( $item_data )) 
					{
						$failCodes [] = $i;
					}
				}
				
				$i ++;
			} else {
				echo json_encode ( array (
						'success' => false,
						'message' => 'Your upload file has no data or not in supported format.' 
				) );
				return;
			}
			
			$success = true;
			if (count ( $failCodes ) > 1) {
				$msg = "Most items imported. But some were not, here is list of their CODE (" . count ( $failCodes ) . "): " . implode ( ", ", $failCodes );
				$success = false;
			} else {
				$msg = "Import items successful";
			}
			
			echo json_encode ( array (
					'success' => $success,
					'message' => $msg 
			) );
		}
	}
	
	/*
	get the width for the add/edit form
	*/
	function get_form_width()
	{
		return 500;
	}
    
    function is_sale_store_item($item_number)
    {  
        echo $this->Item->is_sale_store_item_exist($item_number);        
    }
    
}
?>